package cn.wzx.core.translation.aop.aspect;

import cn.wzx.core.translation.aop.annotation.TransData;
import cn.wzx.core.translation.aop.service.DatabaseTranslator;
import cn.wzx.core.translation.aop.service.RedisTranslator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.lang.reflect.Field;

/**
 * @author wzx
 * @date 2024/11/11 10:29
 * @description: 通过 AOP 拦截带有 TransData 注解的字段，获取相应的值进行翻译
 */
@Aspect
public class TranslationAspect {

    @Resource
    private DatabaseTranslator databaseTranslator;

    @Resource
    private RedisTranslator redisTranslator;

    // 只拦截带有 @EnableTranslation 注解的方法
    @Around("@annotation(cn.wzx.core.translation.aop.annotation.EnableTranslation)")
    public Object translate(ProceedingJoinPoint joinPoint) throws Throwable {
        // 执行目标方法并获取结果
        Object result = joinPoint.proceed();

        // 检查返回对象的字段，执行翻译
        if (result != null) {
            translateFields(result);
        }

        return result;
    }
    private void translateFields(Object result) throws IllegalAccessException {
        // 获取对象的所有字段
        for (Field field : result.getClass().getDeclaredFields()) {
            // 检查字段上是否有 TransData 注解
            TransData transData = field.getAnnotation(TransData.class);
            if (transData != null) {
                // 解析注解信息
                Class<?> entityClass = transData.targetClass();
                String targetField = transData.SqlField();
                String translateField = transData.translateField();
                String redisKey = transData.redisField();
                String type = transData.type();

                // 设置字段为可访问
                field.setAccessible(true);
                Object fieldValue = field.get(result); // 获取原始字段值（待翻译的字段）

                // 根据类型选择翻译方式
                // 使用工厂方法获取相应的 Translator 实例
                Object translatedValue = null;
                if ("mysql".equalsIgnoreCase(type)) {
                    translatedValue = translateFromDatabase(entityClass, targetField, translateField, fieldValue);
                } else if ("redis".equalsIgnoreCase(type)) {
                    translatedValue = translateFromRedis(redisKey, fieldValue);
                }

                // 设置翻译后的值到字段
                if (translatedValue != null) {
                    field.set(result, translatedValue);
                }
            }
        }
    }


    private Object translateFromDatabase(Class<?> entityClass, String targetField, String translateField, Object fieldValue) {
        // 使用 DatabaseTranslator 执行数据库查询
        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(targetField, fieldValue);
        // 查询数据库获取翻译值
        Object result = databaseTranslator.translate(entityClass.getSimpleName(), targetField, "", targetField, translateField);
        if (result != null) {
            try {
                Field translateFieldInEntity = entityClass.getDeclaredField(translateField);
                translateFieldInEntity.setAccessible(true);
                return translateFieldInEntity.get(result);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private Object translateFromRedis(String redisKey, Object fieldValue) {
        // 使用 RedisTranslator 执行 Redis 查询
        return redisTranslator.translate(redisKey, fieldValue.toString());
    }
}
